﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace fenping.package
{
    public class UdpInfo
    {
        private char typeAndProp = ':';
        private char propAndValue = '=';
        private char propAndProp = ';';

        public string Type { get; private set; }
        private Dictionary<string, string> map = new Dictionary<string, string>();
        private List<string> paras = new List<string>();

        public UdpInfo(String message)
        {
            ParseCommand(message);
        }

        public UdpInfo(String message, char typeAndProp, char propAndValue, char propAndProp)
        {
            this.typeAndProp = typeAndProp;
            this.propAndValue = propAndValue;
            this.propAndProp = propAndProp;
            ParseCommand(message);
        }

        private void ParseCommand(string command)
        {
            string[] split = command.Split(typeAndProp);
            Type = split[0].Trim().ToLower();
            if (split.Length > 1)
            {
                split = split[1].Trim().Split(propAndProp);
                for (int i = 0; i < split.Length; i++)
                {
                    string[] kv = split[i].Trim().Split(propAndValue);
                    if(kv.Length == 1)
                    {
                        paras.Add(kv[0].Trim());
                    }
                    else if(kv.Length == 2)
                    {
                        map.Add(kv[0].Trim().ToLower(), kv[1].Trim());
                    }
                }
            }
        }

        public String Get(string key)
        {
            return map[key.Trim().ToLower()];
        }

        public String Get(int index)
        {
            if(paras.Count > index)
            {
                return paras[index];
            }
            else
            {
                throw new Exception("超过参数范围");
            }
        }

        public bool Has(string key)
        {
            return map.ContainsKey(key.Trim().ToLower());
        }

        public bool Has(int index)
        {
            return paras.Count > index;
        }

        public void Add(string value)
        {
            paras.Add(value.Trim());
        }

        public void Add(string key, string value)
        {
            map.Add(key.Trim().ToLower(), value.Trim());
        }

        public override string ToString()
        {
            if(map.Count == 0)
            {
                return Type;
            }
            else
            {
                string parms = String.Join(propAndProp.ToString(), paras.ToArray());
                string props = String.Join(propAndProp.ToString(), map.Select(r => r.Key + propAndValue + r.Value).ToArray());
                return $"{Type}{typeAndProp}{parms}{(parms.Length>0?propAndProp.ToString():"")}{props}";
            }
        }
    }
}
